package com.ldzl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ldzl.dto.BatchStockDTO;
import com.ldzl.dto.QueryInventoryNumDTO;
import com.ldzl.pojo.CkStockDetail;
import com.ldzl.service.CkStockDetailService;
import com.ldzl.mapper.CkStockDetailMapper;
import com.ruoyi.system.api.BasicService;
import com.ruoyi.system.api.domain.BasicUnits;
import com.ruoyi.system.api.domain.BasicWlfl;
import com.ruoyi.system.api.domain.BasicWlfl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.core.exception.ServiceException;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
* @author 风止
* @description 针对表【ck_stock_detail(库存明细表)】的数据库操作Service实现
* @createDate 2025-07-04 11:38:23
*/
@Service
@Transactional
public class CkStockDetailServiceImpl extends ServiceImpl<CkStockDetailMapper, CkStockDetail>
    implements CkStockDetailService{

    @Autowired
    private BasicService bs;

    /**
     * 根据条件分页查询库存明细
     * @param stockDetail
     * @return
     */
    @Override
    public List<CkStockDetail> selectStock(CkStockDetail stockDetail) {
        return super.baseMapper.selectStock(stockDetail);
    }

    /**
     * 查询所有分类
     * @return
     */
    @Override
    public List<BasicWlfl> findWlflz() {
        return bs.selectBasicWlflWithChildren();
    }

    /**
     * 查询单个产品的所有库存
     * @param item_code
     * @return
     */
    @Override
    public QueryInventoryNumDTO queryStock(String item_code) {
        return super.baseMapper.queryStock(item_code);
    }

    /**
     * 查询多个产品的所有库存
     * @param listCode
     * @return
     */
    @Override
    public List<QueryInventoryNumDTO> queryStockList(List<String> listCode) {
        return super.baseMapper.queryStockList(listCode);
    }

    /**
     * 修改库存
     * @param item_code
     * @param quantity_num
     * @return
     */
    @Override
    public boolean updateInventory(String item_code, BigDecimal quantity_num) {
        List<CkStockDetail> listStock = super.list(new QueryWrapper<CkStockDetail>()
                .eq("item_code", item_code)
                .eq("is_delete", 0)
        );
        //需要修改的数据
        List<CkStockDetail> updateList = new ArrayList<>();
        AtomicBoolean isFirst = new AtomicBoolean(true);
        AtomicReference<BigDecimal> num = new AtomicReference<>(BigDecimal.ZERO);
        for (CkStockDetail stock : listStock) {
            if(isFirst.getAndSet(false)){
                //第一个对象
                num.set(stock.getQuantity_num().subtract(quantity_num));
                if (num.get().compareTo(BigDecimal.ZERO) >= 0) {
                    CkStockDetail sd = new CkStockDetail(stock.getItem_id(), num.get());
                    updateList.add(sd);
                    break;
                }
                CkStockDetail sd = new CkStockDetail(stock.getItem_id(), new BigDecimal(0));
                updateList.add(sd);
                continue; //结束本次循环
            }

            num.set(stock.getQuantity_num().add(num.get()));

            // 判断是否大于 0
            if (num.get().compareTo(BigDecimal.ZERO) >= 0) {
                CkStockDetail sd = new CkStockDetail(stock.getItem_id(), num.get());
                updateList.add(sd);
                break;
            }
            CkStockDetail sd = new CkStockDetail(stock.getItem_id(), new BigDecimal(0));
            updateList.add(sd);
        }
        return super.updateBatchById(updateList);
    }

    /**
     * 批量修改库存
     * @param map
     * @return
     */
    @Override
    public boolean updateInventoryBatch(Map<String, BigDecimal> map) {
        List<CkStockDetail> updateList = new ArrayList<>();
        map.forEach((item_code, quantity_num) -> {
            List<CkStockDetail> listStock = super.list(new QueryWrapper<CkStockDetail>()
                    .eq("item_code", item_code)
                    .eq("is_delete", 0)
            );

            if (CollectionUtils.isEmpty(listStock)) {
                throw new ServiceException("物料编码 " + item_code + " 的库存不存在，无法修改。");
            }
            
            AtomicBoolean isFirst = new AtomicBoolean(true);
            AtomicReference<BigDecimal> num = new AtomicReference<>(BigDecimal.ZERO);
            for (CkStockDetail stock : listStock) {
                if(isFirst.getAndSet(false)){
                    //第一个对象
                    num.set(stock.getQuantity_num().subtract(quantity_num));
                    CkStockDetail sd = new CkStockDetail(stock.getItem_id(), new BigDecimal(0));
                    updateList.add(sd);
                    continue; //结束本次循环
                }

                num.set(stock.getQuantity_num().add(num.get()));

                // 判断是否大于 0
                if (num.get().compareTo(BigDecimal.ZERO) >= 0) {
                    CkStockDetail sd = new CkStockDetail(stock.getItem_id(), num.get());
                    updateList.add(sd);
                    break;
                }
                CkStockDetail sd = new CkStockDetail(stock.getItem_id(), new BigDecimal(0));
                updateList.add(sd);
            }
        });
        return super.updateBatchById(updateList);
    }

    /**
     * 增加库存（入库）
     * @param item_code 物料编码
     * @param quantity_num 数量
     * @return
     */
    @Override
    public boolean increaseInventory(String item_code, BigDecimal quantity_num) {
        // 查找最新的库存记录
        CkStockDetail latestStock = super.baseMapper.selectOne(new QueryWrapper<CkStockDetail>()
                .eq("item_code", item_code)
                .orderByDesc("create_time")
                .last("limit 1"));

        if (latestStock != null) {
            // 如果存在，直接增加数量
            latestStock.setQuantity_num(latestStock.getQuantity_num().add(quantity_num));
            return super.updateById(latestStock);
        } else {
            // 如果不存在，需要创建新的库存记录
            // 这里需要更多信息来创建一条完整的 CkStockDetail，例如仓库、批次等
            // 暂时抛出异常，提示需要初始化库存
            throw new ServiceException("物料编码 " + item_code + " 不存在任何库存记录，无法入库。请先初始化库存。");
        }
    }

    /**
     * 修改冻结状态
     * @param id
     * @param frozen_flag
     * @return
     */
    @Override
    public boolean updateFrozen(Long id, String frozen_flag) {
        CkStockDetail stockDetail = new CkStockDetail();
        stockDetail.setItem_id( id);
        stockDetail.setFrozen_flag(frozen_flag);
        return super.saveOrUpdate(stockDetail);
    }

    /**
     * 修改更新人和更新时间
     * @param item_code
     * @param update_by
     * @return
     */
    @Override
    public boolean updateUpdate(String item_code, String update_by) {
        return super.baseMapper.updateUpdate(item_code,update_by) > 0;
    }

    /**
     * 根据物料编码查询批次库存信息
     * 用于派工时批次选择功能
     * @param itemCode 物料编码
     * @return 批次库存列表
     */
    @Override
    public List<BatchStockDTO> selectBatchStockByItemCode(String itemCode) {
        return super.baseMapper.selectBatchStockByItemCode(itemCode);
    }
}




